package com.douqu.game.activity.server.rmi;

import com.douqu.game.activity.gui.MainFrame;
import com.douqu.game.core.factory.ConfigFactory;
import com.douqu.game.core.i.IMainServer;
import com.douqu.game.core.i.IServer;
import com.douqu.game.core.rmi.MyRMISocket;
import com.douqu.game.core.util.LogUtils;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.RMISocketFactory;

/**
* Created by bean
* 2017-03-24 12:26.
*/
public class RMIServer implements IServer{


    @Override
    public void start()
    {
        try {

            RMISocketFactory.setSocketFactory(new MyRMISocket());

            IMainServer gameManager = new ActivityServerImpl();

            LocateRegistry.createRegistry(ConfigFactory.SERVER_PORT_RMI);

            Naming.bind(ConfigFactory.SERVER_URL_RMI, gameManager);

            LogUtils.info("Start RMI Server Success ------ 【" + ConfigFactory.SERVER_URL_RMI + "】");
            MainFrame.println("Start RMI Server Success ------ 【" + ConfigFactory.SERVER_URL_RMI + "】");

        } catch (Exception e) {
            LogUtils.error("创建远程对象发生异常！");
            e.printStackTrace();
        }
    }

    @Override
    public boolean isRunning()
    {
//        try {
//            Naming.lookup(ConfigFactory.SERVER_URL_RMI);
//            return true;
//        } catch (Exception e) {
//            return false;
//        }
        return true;
    }


    @Override
    public synchronized void stop()
    {
        try {

            Naming.unbind(ConfigFactory.SERVER_URL_RMI);

            LogUtils.info("Stop RMI Server Success ------ " + ConfigFactory.SERVER_URL_RMI);
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (NotBoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        new RMIServer().start();
    }

}
